import 'dart:async';
import 'dart:convert';

import 'package:flutter/services.dart';

import 'aj_flutter_appsp_lib.dart';

/// Copyright © 2018 anji-plus
/// 安吉加加信息技术有限公司
/// http:///www.anji-plus.com
/// All rights reserved.
/// AppSp功能
///
typedef OnApkDownloadProgressCallback = void Function(dynamic result);

class AjFlutterAppSp {
  OnApkDownloadProgressCallback _apkDownloadProgressCallback;
  static const MethodChannel _channel = const MethodChannel('aj_flutter_appsp');

  AjFlutterAppSp() {
    print("AjFlutterAppspPush constructor");
    _channel.setMethodCallHandler(_handlerMethodCallback);
  }

  ///下载进度回调
  void getApkDownloadProgressCallback(OnApkDownloadProgressCallback callback) {
    if (callback == null) {
      return;
    }
    this._apkDownloadProgressCallback = callback;
  }

  /// native - flutter
  Future<dynamic> _handlerMethodCallback(MethodCall call) async {
    switch (call.method) {
      case "updateProgress":
        dynamic result = call.arguments;
        if (_apkDownloadProgressCallback != null) {
          _apkDownloadProgressCallback(result);
        }
        break;
      default:
        break;
    }
  }

  ///设置基础地址，如果在开发测试场景会用到，生产时候记得改成生产地址，或者最好不要对暴露set方法
  ///[appKey] 应用唯一标识
  ///[host] 设置请求基础地址
  ///[debug] 是否打开日志开关，true为打开
  static Future<String> init(
      {String appKey = '', String host = '', bool debug = true}) async {
    final String result = await _channel
        .invokeMethod('init', {"appKey": appKey, "host": host, "debug": debug});
    return result;
  }

  ///获取版本信息
  static Future<SpRespUpdateModel> getUpdateModel() async {
    final String jsonStr = await _channel.invokeMethod('getUpdateModel');
    SpRespUpdateModel updateModel =
        SpRespUpdateModel.fromJson(json.decode(jsonStr));
    return updateModel;
  }

  ///获取公告信息
  static Future<SpRespNoticeModel> getNoticeModel() async {
    final String jsonStr = await _channel.invokeMethod('getNoticeModel');
    SpRespNoticeModel noticeModel =
        SpRespNoticeModel.fromJson(json.decode(jsonStr));
    return noticeModel;
  }

  ///下载apk并且安装
  ///返回 ”UrlFormatError“ =》url格式错误
  ///返回 ”notSamePackage“ =》不是统一包名
  ///返回 ”downloadApkFailed“ =》apk下载失败
  Future<String> downloadApkAndInstall(String url, String path) async {
    final String result = await _channel
        .invokeMethod('downloadApkAndInstall', {"url": url, "path": path});
    return result;
  }

  ///apk安装
  ///返回 ”FilePathFormatError“ =》文件格式错误
  Future<String> installApk(String path) async {
    final String result =
        await _channel.invokeMethod('installApk', {"path": path});
    return result;
  }

  ///apk下载取消
  Future<String> cancelDownload() async {
    final String result = await _channel.invokeMethod('cancelDownload');
    return result;
  }

  ///是否同一包名
  Future<String> checkSamePackage(String path) async {
    final String result =
        await _channel.invokeMethod('checkSamePackage', {"path": path});
    return result;
  }
}
